<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script>

  var geocoder;
  var map;
  var autocomplete;
  var markers = [];

  function initialize() {

    document.getElementById("latlng").value="<?=$address->long.','.$address->lat ?>";
    document.getElementById("address").value="<?=$address->address ?>";
    document.getElementById("string").value="<?=$address->google_add ?>";
    document.getElementById("city").value="<?=$address->city ?>";
    document.getElementById("region").value="<?=$address->region ?>";

    var input = document.getElementById('address');
    var options = {
      componentRestrictions: { country: 'ph' }
  };

    autocomplete = new google.maps.places.Autocomplete(input, options);

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      codeAddress(); 

  });

    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(14.561, 121.026);
    var mapOptions = {
      zoom: 15,
      center: latlng
    }

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    codeAddress();
  }

  function codeAddress() {

  var iconBase = 'behomebased-ph/Design/Final/Photos/Icon';

  var address = document.getElementById('address').value;
   geocoder.geocode( { 'address': address, 'componentRestrictions':{'country':'ph'}}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            icon: iconBase + 'Marker.png',
            position: results[0].geometry.location,
            draggable:true,

        });
        markers.push(marker);

        var coordinates = marker.getPosition();
        coordinates1 = coordinates.toString();
        coordinates2 = coordinates1.substring(1, coordinates1.length-1);
        document.getElementById("latlng").value = coordinates2; 
        document.getElementById("latlng").focus();    
      

        google.maps.event.addListener(marker, 'dragend', function() {
        var coordinates = marker.getPosition();
        coordinates1 = coordinates.toString();
        coordinates2 = coordinates1.substring(1, coordinates1.length-1);
        document.getElementById("latlng").value = coordinates2;  
        document.getElementById("latlng").focus(); 
        map.setCenter(coordinates);   

        setTimeout(get, 230);

        function get(){
  document.getElementById('address').value = document.getElementById('string').value;
  }
          setTimeout(get, 230);
  });

      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }

    });


  }

  function setAllMap(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }

  // Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setAllMap(null);
  }

  function deleteMarkers() {
    clearMarkers();
    markers = [];
  }



  function codeLatLng() {

    var input = document.getElementById('latlng').value;
    var latlngStr = input.split(',', 2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    var string;

    
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {

          for (var j=0; j<results.length; j++)
          {

          for (var i=0; i<results[j].address_components.length; i++)
              {
                  if (results[j].address_components[i].types[0] == "locality") {
                          //this is the object you are looking for
                          city = results[j].address_components[i];
                      }
                  if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
                          //this is the object you are looking for
                          region = results[j].address_components[i];
                      }
              }
            }

      string = (results[0].formatted_address);
      document.getElementById("string").value = string;
      document.getElementById("city").value=  city.long_name;
      document.getElementById("region").value=  region.long_name;

       if (document.getElementById("region").value == "Metro Manila")
       {
        (document.getElementById("region").value = "National Capital Region");
       }


      /*var city_name = document.getElementById("city").value;

      if (city_name.substr(-4, 4) == "City")
          {
            cityname == city_name.substr(0,length-5);
            document.getElementById("city").value == cityname;
          }

          else if (city_name.substr(0,7) == "City of")
            {
             city_name = city_name.substr(8,length);
              $('#city').val(city_name);
            }
            
             else 
             { 

             }*/

        } else {
          alert('No results found');
        }
      
      } else {
       
      }

    });

  }

  function cleartext(){
    document.getElementById("address").value="";
    document.getElementById("latlng").value="";
    document.getElementById("string").value="";
    document.getElementById("city").value="";
    document.getElementById("region").value="";
    deleteMarkers();
  }

  google.maps.event.addDomListener(window, 'load', initialize);

</script>

<div class="row">
  <div class="step-wrapper large-10 large-centered column">
    <div class="stpy large-12 column">

      <div class="step-statement large-4 columns">
        <h5>User Registration</h5>
        <p>Locate your Address to find people nearby you. </p>
      </div>  

      <div class="stepbystep  large-8 columns">
        <div class="right ui ordered  small steps">
          <div class="animated slideInRight completed step">
            <div class="content">
              <div class="title"></div>
              <div class="description">Basic Information</div>
            </div>
          </div>
<style type="text/css">
.completed {

}
</style>

          <div class="active step">
            <div class="content">
              <div class="title"></div>
              <div class="description">Address</div>
            </div>
          </div>
          <div class="disabled step">
            <div class="content">
              <div class="title"></div>
              <div class="description">Education</div>
            </div>
          </div>
          <div class="disabled step">
            <div class="content">
              <div class="title"></div>
              <div class="description">Work Experience</div>
            </div>
          </div>         
        </div>
      </div>

      <div class="hr-reg large-12 column"><hr></div>

      <div class="large-12 column">
        <div class="large-6 column">
          <input id="address" type="text" placeholder="Search Address" onClick="cleartext();" size=70>
        </div>
        <div class="map-reg large-6 columns" style="margin-bottom:1rem;padding:0 2rem 0 2rem;">
          <div id="map-canvas" class="large-12 column" style="background:gray;height:320px;border-radius:.34rem;"></div>     
        </div>
      </div>

      <div class="large-12 column" style="padding:0;margin-top:1rem;">
          <div class="btn-save text-left large-8 columns" style="padding:0;">
            <a href="<?=BASE_URI ?>registration/step_1" class="text-left button">Previous</a>     
          </div>
          <div class="btn-save text-right large-4 columns" style="padding:0;"> 
            <a id="btnSaveStep2"  class="button">Next</a>
          </div>
      </div>

    </div>
  </div>
</div>

<div class="large-3 columns" style="opacity: 0.0;">
  <input id="latlng" type="text" onfocus="codeLatLng()" onchange="codeLatLng()" size=30 readonly><br>
  <input id="string" type="text" size=30 readonly><br>
  <input id="region" type="text" size=30 readonly><br>
  <input id="city" type="text" size=30 readonly><br>
</div>

<script>
$(document).ready(function(){
initialize();
});
</script>

<script type="text/javascript">
    function saveStep2(address,longt,lat,google_add,region,city)
    {
        var params = {};
        params['address'] = address;
        params['longt'] = longt;
        params['lat'] = lat;
        params['google_add'] = google_add;
        params['region'] = region;
        params['city'] = city;

      
        return $.ajax({
          url: URL + 'registration/save/step_2',
          type: 'post',
          data: params,
          dataType: 'json'         
        });
    }

    var nextUrl = URL + "registration/step_3";
    var $btnSave = $('#btnSaveStep2');
    
    $btnSave.on('click',function(){
        var address = $('#address').val();
        var latLng = $('#latlng').val();
        var google_address = $('#string').val();
        var region = $('#region').val();
        var city = $('#city').val();
        var longLat = latLng.split(",");
        
        saveStep2(address,longLat[1],longLat[0],google_address,region,city).done(function(result){
            if(result.status == false)
            {
                alert(result.messages);
            }
            else if(result.status == true)
            {
                window.location.replace(nextUrl); 
            }
            else
            {
                alert("Something went wrong.");
            }
        });
        
       
    });
</script>

<style>
body {
  background: #F5F5F5 !important;
  height: 100%;
  overflow: hidden;
}
</style>